import { reqAddOrUpdateShopCart,reqShopCartInfo ,reqUpdateCartIscheck,reqDeleteShopCart} from '@/network';

const state = {
    shopCartInfo: []
}


const actions = {
    async addOrUpdateShopCart({commit},{skuId,skuNum}){
        const result = await reqAddOrUpdateShopCart(skuId,skuNum);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
  
   
    },
     async getShopCartInfo({commit}) {
        const result = await reqShopCartInfo();
        if(result.code === 200) {
            commit('RECEIVE_SHOPCARTINFO',result.data)
        }

    },
    async updateCartIscheck({commit},{skuId,isChecked}) {
        const result = await reqUpdateCartIscheck(skuId,isChecked);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }

    },
    updateCartIscheckAll({commit,getters,dispatch},isChecked) {
        let promises = []
        getters.cartInfo.cartInfoList.forEach(item => {
            if(item.isChecked === isChecked) return
            let promise = dispatch('updateCartIscheck',{skuId:item.skuId,isChecked});
            promises.push(promise)
        })
        return Promise.all(promises)
    },
    async deleteShopCart({commit},skuId) {
        const result = await reqDeleteShopCart(skuId);
         if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    deleteShopCartAll({commit,getters,dispatch},isChecked) {
        let promises = []
        getters.cartInfo.cartInfoList.forEach(item => {
            if(!item.isChecked) return
            let promise = dispatch('deleteShopCart',item.skuId);
            promises.push(promise)
        })
        return Promise.all(promises)
    },
    
}

const mutations = {
    RECEIVE_SHOPCARTINFO(state,shopCartInfo) {
        state.shopCartInfo = shopCartInfo;
    }
}

const getters = {
    cartInfo(state) {
            return state.shopCartInfo[0] || {}
        }   
}

export default {
    state,
    actions,
    mutations,
    getters
}